import sys
import auto_log
import auto_utility
import auto_vm
import auto_test
import time
import shutil
import os

try:
    path = sys.argv[1]
except:
    print("usage example: real2.py task.xml")

client_log = "autotest_results.xml"
id_install = "msi_install"
id_test = "test"

vmrun = ""
vmmount = ""
letter = ""
floppy = ""
modules = ""
utilities = ""
client_msi_logs = ""
vmx_path = ""
vm_scripts_folder = ""
vm_logs_folder = ""
snapshot_for_install = ""
msi_path = ""
serial = ""
main_install = ""
main_test = ""
server_log = ""
install_limit = 0
test_limit = 0

def get_settings(path):
    from auto_test import auto_read_setting
    #--------------------------------------------
    global vmx_path#done
    global vm_scripts_folder#done
    global vm_logs_folder#done
    global snapshot_for_install#done
    
    global msi_path#done
    global serial#done
    
    global main_install#done
    global main_test#done
    
    global modules#done
    global utilities#done
    
    global server_log#done
    global client_msi_logs#done
    
    global vmrun#done
    global vmmount#done
    global letter#done
    global floppy#done
    
    global install_limit
    global test_limit
    #--------------------------------------------
    setting = "server_log"
    server_log = auto_read_setting(path, setting)["res"]
    if server_log == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        return message
    print(setting, server_log)
    #--------------------------------------------
    setting = "vmrun"
    vmrun = auto_read_setting(path, setting)["res"]
    if vmrun == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, vmrun)
    #--------------------------------------------
    setting = "vmmount"
    vmmount = auto_read_setting(path, setting)["res"]
    if vmmount == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, vmmount)
    #--------------------------------------------
    setting = "letter"
    letter = auto_read_setting(path, setting)["res"]
    if letter == "":
        message = "Can't read " + setting + " from " + path
        print(setting, message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, letter)
    #--------------------------------------------
    setting = "modules"
    modules = auto_read_setting(path, setting)["res"]
    if modules == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, modules)
    #--------------------------------------------
    setting = "utilities"
    utilities = auto_read_setting(path, setting)["res"]
    if utilities == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, utilities)
    #--------------------------------------------
    setting = "client_msi_logs"
    client_msi_logs = auto_read_setting(path, setting)["res"]
    if client_msi_logs == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, client_msi_logs) 
    #--------------------------------------------
    setting = "vmx_path"
    vmx_path = auto_read_setting(path, setting)["res"]
    if vmx_path == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, vmx_path)
    #--------------------------------------------
    setting = "vm_scripts_folder"
    vm_scripts_folder = auto_read_setting(path, setting)["res"]
    if vm_scripts_folder == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, vm_scripts_folder)
    #--------------------------------------------
    setting = "vm_logs_folder"
    vm_logs_folder = auto_read_setting(path, setting)["res"]
    if vm_logs_folder == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, vm_logs_folder)
    #--------------------------------------------
    setting = "snapshot_for_install"
    snapshot_for_install = auto_read_setting(path, setting)["res"]
    if snapshot_for_install == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, snapshot_for_install)
    #--------------------------------------------
    setting = "msi_path"
    msi_path = auto_read_setting(path, setting)["res"]
    if msi_path == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, msi_path)
    #--------------------------------------------
    setting = "serial"
    serial = auto_read_setting(path, setting)["res"]
    if serial == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, serial)
    #--------------------------------------------
    setting = "main_install"
    main_install = auto_read_setting(path, setting)["res"]
    if main_install == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, main_install)
    #--------------------------------------------
    setting = "main_test"
    main_test = auto_read_setting(path, setting)["res"]
    if main_test == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, main_test)
    #--------------------------------------------
    setting = "floppy"
    floppy = auto_read_setting(path, setting)["res"]
    if floppy == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, floppy)
    #--------------------------------------------
    setting = "install_limit"
    install_limit = auto_read_setting(path, setting)["res"]
    if install_limit == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    #------------------
    try:
        install_limit = int(install_limit)
        if install_limit <= 0:
            message = "Incorrect setting in task = " + install_limit + "\n" + setting + " must be positive integer!"
            print(message)
            auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
            return message
    except:
        message = "Incorrect setting in task = " + install_limit + "\n" + setting + " must be positive integer!"
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, install_limit)
    #--------------------------------------------
    setting = "test_limit"
    test_limit = auto_read_setting(path, setting)["res"]
    if test_limit == "":
        message = "Can't read " + setting + " from " + path
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    #------------------
    try:
        test_limit = int(test_limit)
        if test_limit <= 0:
            message = "Incorrect setting in task = " + test_limit + "\n" + setting + " must be positive integer!"
            print(message)
            auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
            return message
    except:
        message = "Incorrect setting in task = " + test_limit + "\n" + setting + " must be positive integer!"
        print(message)
        auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, "read setting " + setting + " from file")
        return message
    print(setting, test_limit)
    #--------------------------------------------
    
    return 0
#----------------------------------------------------------------------

def parse_installation_results(folder):
    return 0
#----------------------------------------------------------------------

def parse_test_results(path):
    return 0
#----------------------------------------------------------------------

def xml_result_2_html_result(path, html_log):
    import xml.etree.ElementTree as etree
    tree = etree.parse(path)
    root = tree.getroot()
    
    all_tests = 0
    all_failed_tests = 0
    all_ok_tests = 0
    all_performance = 0
    
    
    error_data = ""
    
    data = '<html><body>'
    #---------------------------------------
    records_list = root.findall("record")
    table_data = ""
    
    msi_vmx = ""
    msi_vmx_tests = 0
    msi_vmx_failed_tests = 0
    msi_vmx_ok_tests = 0
    msi_vmx_performance = 0
    
    for item in records_list:
        if item.get("id") == id_test:
            msi = item.text.split("msi = ")[1].split("\n")[0].split("\\")[-1][0:-4]
            vmx = item.text.split("vmx = ")[1].split("\n")[0].split("\\")[-1][0:-4]
            
            if (msi + vmx) != msi_vmx:
                if table_data != "":
                    
                    table_data = table_data + '<tr bgcolor="#d9ffd9"><td>&nbsp</td><td>&nbsp</td><td><b>number of tests = %s</b></td><td><b>failed = %s. ok = %s</b></td><td><b>%s</b></td></tr>' % (str(msi_vmx_tests), str(msi_vmx_failed_tests), str(msi_vmx_ok_tests), str(msi_vmx_performance))
                    table_data = table_data + "</table>"
                    
                    table_data = table_data + "<br>"
                    
                    table_data = table_data + '<table border="1"; cellspacing="0"; cellpadding="3"><tr bgcolor="#66ff33"><th>msi</th><th>configuration</th><th>script</th><th>result</th><th>seconds for test</th></tr>'
                    
                else:
                    table_data = table_data + '<table border="1"; cellspacing="0"; cellpadding="3"><tr bgcolor="#66ff33"><th>msi</th><th>configuration</th><th>script</th><th>result</th><th>seconds for test</th></tr>'
                msi_vmx = msi + vmx
                msi_vmx_tests = 0
                msi_vmx_failed_tests = 0
                msi_vmx_ok_tests = 0
                msi_vmx_performance = 0
                
            script = item.text.split("script = ")[1].split("\n")[0].split("\\")[-1][0:-4]
            time_for_test = item.text.split("time for test = ")[1].split("\n")[0]
            all_performance = all_performance + float(time_for_test)
            msi_vmx_performance = msi_vmx_performance + float(time_for_test)
            if item.get("status") == auto_log.STATUS_OK:
                result_color = "green"
                result = "<b>Ok</b>"
                all_ok_tests += 1
                msi_vmx_ok_tests += 1
            else:
                result_color = "red"
                result = item.text.replace("\n", "<br>")
                error_link = 'Error description for msi = %s, configuration = %s, script = %s' % (msi, vmx, script)
                error_data = error_data + '<a name="%s"><h4>%s</h4></a>' % (error_link, error_link)
                error_data = error_data + '<table border = "1"; cellspacing="0"><tr style = "font-size: 80%%; font-family: sans-serif"><td nowrap>%s</td></tr></table><br>' % (result)
                result = '<b>Error </b><a href="#%s">more details</a>' % (error_link)
                all_failed_tests += 1
                msi_vmx_failed_tests += 1
            table_data = table_data + '<tr><td>%s</td><td>%s</td><td>%s</td><td style = "color:%s">%s</td><td>%s</td></tr>' % (msi, vmx, script, result_color, result, time_for_test)
            all_tests += 1
            msi_vmx_tests += 1
    #---------------------------------------
    table_data = table_data + '<tr bgcolor="#d9ffd9"><td>&nbsp</td><td>&nbsp</td><td><b>number of tests = %s</b></td><td><b>failed = %s. ok = %s</b></td><td><b>%s</b></td></tr>' % (str(msi_vmx_tests), str(msi_vmx_failed_tests), str(msi_vmx_ok_tests), str(msi_vmx_performance))
    table_data = table_data + "</table>"
    
    table_data = table_data + "<br>"
    
    
    data = data + '<h2>Test metrics</h2>'
    data = data + '<h4>Number of all tests = ' + str(all_tests) + '</h4>'
    data = data + '<h4 style = "color:red">Number of tests failed with error = ' + str(all_failed_tests) + '</h4>'
    data = data + '<h4 style = "color:green">Number of tests completed successfully = ' + str(all_ok_tests) + '</h4>'
    data = data + '<h4>Time for all tests = ' + str(all_performance) + '</h4>'
    data = data + '<h2>Test results</h2>'
    data = data + table_data + error_data + "</body></html>"
    file = open(html_log, "w")
    file.write(data)
    file.close()
#---------------------------------------


#Main program
#get_settings
result = get_settings(path)
if result != 0:
    exit(-1)
#--------------------------------------------
#get list of *.vmx from vmx_path
result = auto_utility.files_list_from_path(vmx_path, ".vmx", server_log)
if result["res"] == []:
    print("Can not find any *.vmx in " + vmx_path)
    exit(-2)
vmx_list = result["res"]
#--------------------------------------------
#get list of *.msi from msi_path
result = auto_utility.files_list_from_path(msi_path, ".msi", server_log)
if result["res"] == []:
    print("Can not find any *.msi in " + msi_path)
    exit(-3)
msi_list = result["res"]
#--------------------------------------------
auto_vm.vm_unmount(vmmount, letter, "")
#install all msi to all vmx
#--------------------------------------------
for msi in msi_list:
    for vmx in vmx_list:
        #revert to snapshot before install
        revert = auto_vm.vm_revert(vmrun, vmx, snapshot_for_install, server_log)
        #--------------------------------------------
        if revert == 0:
            #install msi to vmx
            logs = client_msi_logs + "\\" + vmx.split("\\")[-1][0:-4] + "_" + msi.split("\\")[-1][0:-4]
            install = auto_test.run_vmx_test(vmrun, vmmount, vmx, logs, letter, modules, utilities, "", [msi, serial], main_install, "", install_limit, server_log)
            #--------------------------------------------
            if install == 0:
                #check install results
                msi_log = auto_utility.file_from_path(logs, "msi_install.log", server_log)["res"]
                #--------------------------------------------
                if auto_log.msi_msiexec_result(msi_log, server_log)["res"].count("success") != 0:
                    message = "vmx = " + vmx + "\nmsi = " + msi + "\nInstallation completed successfully!"
                    print(message)
                    auto_log.write_result(server_log, message, auto_log.STATUS_OK, id_install)
                    #get paths 
                    vmx_name = vmx.split("\\")[-1]
                    scripts_folder = vmx.split(vmx_name)[0] + vm_scripts_folder
                    logs = vmx.split(vmx_name)[0] + vm_logs_folder + "\\" + msi.split("\\")[-1][0:-4]                    
                    #--------------------------------------------
                    #parameters for vmware.py (path to scripts.exe + path to layout.ini)
                    parameters = '"%s" "%s"' % (auto_log.msi_file_path_from_log(msi_log, "scripts.exe", server_log)["res"], auto_log.msi_file_path_from_log(msi_log, "layout.ini", server_log)["res"])
                    #--------------------------------------------
                    #create snapshot for testing
                    snapname = "AutoTestSnapshot_" + str(time.time())
                    auto_vm.vm_create_snapshot(vmrun, vmx, snapname, server_log)
                    #--------------------------------------------
                    logs_folder = logs
                    script_list = auto_utility.files_list_from_path(scripts_folder, ".psl", server_log)["res"]
                    for script in script_list:
                        #logs = logs_folder + "\\" + script.split("\\")[-1][0:-4]
                        logs = logs_folder + script.split(scripts_folder)[1][0:-4]
                        if not os.path.exists(logs):
                            os.makedirs(logs)
                            #----------------------------------------------------------
                            auto_vm.vm_revert(vmrun, vmx, snapname, server_log)
                            #----------------------------------------------------------
                            shutil.copy2(floppy, vmx.split(vmx_name)[0])
                            #----------------------------------------------------------
                            t0 = time.time()
                            test = auto_test.run_vmx_test(vmrun, vmmount, vmx, logs, letter, "", "", "", [script], main_test, parameters, test_limit, server_log)
                            time_for_test = str(time.time() - t0)
                            #----------------------------------------------------------
                            shutil.copy2(floppy, vmx.split(vmx_name)[0])
                            #----------------------------------------------------------
                            if test == 0:
                                #parse results
                                test_log = auto_utility.file_from_path(logs, client_log, server_log)["res"]
                                try:
                                    file = open(test_log, "r")
                                    data = file.read()
                                    file.close()
                                except:
                                    message = "vmx = " + vmx + "\nmsi = " + msi + "\nscript = " + script + "\ntime for test = " + time_for_test + "\n\nTest completed with errors:\n"
                                    message = message + "No logs!"
                                    print(message)
                                    auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, id_test)
                                    xml_result_2_html_result(server_log, server_log[0:-4] + ".html")
                                    continue
                                if data.count("Script completes succesfully") != 0:
                                    message = "vmx = " + vmx + "\nmsi = " + msi + "\nscript = " + script + "\ntime for test = " + time_for_test + "\nTest successfully completed"
                                    print(message)
                                    auto_log.write_result(server_log, message, auto_log.STATUS_OK, id_test)
                                else:
                                    message = "vmx = " + vmx + "\nmsi = " + msi + "\nscript = " + script + "\ntime for test = " + time_for_test + "\nTest completed with errors:\n"
                                    #------------------------------------
                                    import xml.etree.ElementTree as etree
                                    
                                    tree = etree.parse(test_log)
                                    root = tree.getroot()
                                    
                                    data = ""
                                    records_list = root.findall("record")
                                    for item in records_list:
                                        if item.get("status") == auto_log.STATUS_ERROR:
                                            data = data + item.text
                                    #------------------------------------
                                    message = message + data
                                    print(message)
                                    auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, id_test)
                            else:
                                message = "vmx = " + vmx + "\nmsi = " + msi + "\nscript = " + script + "\ntime for test = " + time_for_test + "\n"
                                message = message + "run_vmx_test error:" + test
                                print(message)
                                auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, id_test)
                            xml_result_2_html_result(server_log, server_log[0:-4] + ".html")
                    #-------------------------------------------------------------------------------
                    auto_vm.vm_delete_snapshot(vmrun, vmx, snapname, server_log)
                else:
                    message = "vmx = " + vmx + "\nmsi = " + msi + "\nInstallation failed with errors!\n"
                    message = message + "See " + logs + " for information"
                    print(message)
                    auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, id_install)
            else:
                message = "vmx = " + vmx + "\nmsi = " + msi + "\nInstallation failed with errors!\n"
                message = message + install
                print(message)
                auto_log.write_result(server_log, message, auto_log.STATUS_ERROR, id_install)
        else:
            print(revert)
#--------------------------------------------